<?php


namespace app\admin\controller\User;


use app\admin\controller\BaseController;
use app\admin\model\User\UserWithdrawModel;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\Request;

class UserWithdraw extends BaseController
{

    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getUserWithdrawList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] :10;
        $status = !empty($param['status']) ? $param['status'] : 0;

        if (!empty($status)) {
            array_push($where, ['status', '=', $status]);
        }

        $list = UserWithdrawModel::getUserWithdrawListWhere($page, $limit, $where,'uw.*,u.nickname');
        $count = UserWithdrawModel::getUserWithdrawCountWhere($where);

        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");
    }

    /**
     * 微信提现
     * @param Request $request
     * @return array
     */
    public function getUserWithdrawWxPay(Request $request)
    {
        $param = request()->param();
        if(empty($param['id']) || !isset($param['id'])){
            return Util::returnJson(self::CODE_ERROR, null, "参数错误");
        }
        $withdraw = UserWithdrawModel::getWithdrawWhere(['uw.id'=>$param['id']],'uw.*,u.openId');
        if(!empty($withdraw)){
            if(!($withdraw['type'] === 1)){
                return Util::returnJson(self::CODE_ERROR, null, "提现方式错误");
            }
            if(!($withdraw['state'] === 1)){
                return Util::returnJson(self::CODE_ERROR, null, "提现记录已处理");
            }
            //获取配置信息
            $config = config('weixin.weixin_api');

            Db::startTrans();
            try{
                $webdata = [
                    'mch_appid'         => $config['appid'],//商户账号appid
                    'mchid'             => $config['mch_id'],//商户号
                    'nonce_str'         => md5(time()),//随机字符串
                    'partner_trade_no'  => $withdraw['withdraw_id'], //商户订单号，需要唯一
                    'openid'            => $withdraw['openId'],//转账用户的openid
                    'check_name'        => 'NO_CHECK', //OPTION_CHECK不强制校验真实姓名, FORCE_CHECK：强制 NO_CHECK：
                    'amount'            => $withdraw['amount']*100, //付款金额单位为分
                    'desc'              => '用户提现金额 '.$withdraw['amount'].'元',//企业付款描述信息
                    'spbill_create_ip'  => request()->ip(),//获取IP
                ];
                foreach ($webdata as $k => $v) {
                    $tarr[] =$k.'='.$v;
                }
                sort($tarr);
                $sign = implode($tarr, '&');
                $sign .= '&key='.$config['key'];
                $webdata['sign']=strtoupper(md5($sign));
                //数组转XML
                $wget = Util::arrayToXml($webdata);
                $pay_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';//api地址
                //发送数据
                $res = Util::postWxData($pay_url,$wget);
                if(!$res){
                    $save = [
                        'state'=>10,
                        'handle_time'=>date("Y-m-d H:i:s",time()),
                        'remark'=>"Can't connect the server",
                    ];
                    UserWithdrawModel::updateUserWithdrawWhere(['id'=>$withdraw['id']],$save);
                    return Util::returnJson(self::CODE_ERROR, null, "Can't connect the server");
                }
                $content = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
                if(strval($content->return_code) == 'FAIL'){
                    $save = [
                        'state'=>10,
                        'handle_time'=>date("Y-m-d H:i:s",time()),
                        'remark'=>strval($content->return_msg),
                    ];
                    UserWithdrawModel::updateUserWithdrawWhere(['id'=>$withdraw['id']],$save);
                    return Util::returnJson(self::CODE_ERROR, null, strval($content->return_msg));
                }
                if(strval($content->result_code) == 'FAIL'){
                    $save = [
                        'state'=>10,
                        'handle_time'=>date("Y-m-d H:i:s",time()),
                        'remark'=>strval($content->err_code).':'.strval($content->err_code_des),
                    ];
                    UserWithdrawModel::updateUserWithdrawWhere(['id'=>$withdraw['id']],$save);
                    return Util::returnJson(self::CODE_ERROR, null, strval($content->err_code).':'.strval($content->err_code_des));
                }
                $rdata = [
                    'mch_appid'        => strval($content->mch_appid),
                    'mchid'            => strval($content->mchid),
                    'device_info'      => strval($content->device_info),
                    'nonce_str'        => strval($content->nonce_str),
                    'result_code'      => strval($content->result_code),
                    'partner_trade_no' => strval($content->partner_trade_no),
                    'payment_no'       => strval($content->payment_no),
                    'payment_time'     => strval($content->payment_time),
                ];
                $save = array(
                    'state'=>5,
                    'handle_time'=>date("Y-m-d H:i:s",time()),
                    'payment_no'=>$rdata['payment_no']
                );
                $flag = UserWithdrawModel::updateUserWithdrawWhere(['id'=>$withdraw['id']],$save);
                if($flag){
                    Db::commit();
                    return Util::returnJson(self::CODE_ERROR, null, "提现成功");
                }else{
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR, null, "提现失败");
                }
            }catch (Exception $e){
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR, null, "提现失败");
            }
        }else{
            return Util::returnJson(self::CODE_ERROR, null, "提现错误");
        }
    }

}